package com.xinlianshiye.im.controller;

import com.xinlianshiye.im.Result;
import com.xinlianshiye.im.service.UserService;
import com.xinlianshiye.im.utils.SessionManager;
import com.xinlianshiye.im.websocket.WebSocketController;
import com.xinlianshiye.im.websocket.WebSocketRequestMapping;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@WebSocketController
@RestController
@RequestMapping("im/user")
public class IMUserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SessionManager sessionManager;

    @GetMapping("online")
    public Map<Integer, List<String>> online() {
        return sessionManager.getUserOnline().keySet().stream().collect(Collectors.toMap(
                userId -> userId,
                userId -> sessionManager.getSessionByUserId(userId).stream().map(Session::getId).collect(Collectors.toList())
        ));
    }

    /**
     * 用户登录初始化数据
     */
    @WebSocketRequestMapping("init")
    public void init(Session session) {
        userService.sendInit(userService.getUserId(session));
    }

    /**
     * 修改个性签名信息
     */
    @WebSocketRequestMapping("updSign")
    public Result updSign(@RequestParam String sign, Session session) {
        return Result.success(userService.updSign(userService.getUserId(session), sign));
    }

    /**
     * 根据用户id 获取用户信息 以及对应的聊天信息
     *
     * @return
     */
    @WebSocketRequestMapping("getSSOIdUserAndRecord")
    public Result getSSOIdUserAndRecord(@RequestParam Integer topic, Session session) throws Exception {
        return Result.success(userService.getTemporaryContactAndRecord(userService.getUserId(session), topic));
    }

    /**
     * 根据用户id 显示用户好友聊天列表 根据是否读取过 排序 未读取优先级高 好友分组 取最新一条数据 有几条未查阅的信息
     */
    @WebSocketRequestMapping("findUseridRecordCustom")
    public Result findUseridRecordCustom(String search, Session session) {
        return Result.success(userService.findUseridRecordCustom(userService.getUserId(session), search));
    }

    /**
     * 修改名称
     */
    @WebSocketRequestMapping("updName")
    public Result updName(@RequestParam String name, Session session) {
        return Result.success(userService.updName(userService.getUserId(session), name));
    }

    /**
     * 修改头像
     */
    @WebSocketRequestMapping("updAvatar")
    public Result updAvatar(@RequestParam String avatar, Session session) {
        return Result.success(userService.updAvatar(userService.getUserId(session), avatar));
    }
}
